package com.itany.netclass.service.impl;

import com.itany.mvc.util.CommonsMultipartFile;
import com.itany.netclass.constant.CourseConstant;
import com.itany.netclass.constant.ResourceConstant;
import com.itany.netclass.dao.ChapterMapper;
import com.itany.netclass.dao.CourseMapper;
import com.itany.netclass.dao.ResourceMapper;
import com.itany.netclass.entity.*;
import com.itany.netclass.exception.*;
import com.itany.netclass.factory.ObjectFactory;
import com.itany.netclass.service.ChapterService;
import com.itany.netclass.service.ResourceService;
import com.itany.netclass.util.ParameterUtil;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Author:sjy@itany.com
 * Date:2021/10/16 18:49
 * Version:1.0-SNAPSHOT
 */
public class ChapterServiceImpl implements ChapterService {
    @Override
    public List<Chapter> findAllChapterByCourseId(String courseId) throws NullSringException {
        ChapterMapper chapterMapper= (ChapterMapper) ObjectFactory.getObject("ChapterMapper");
        ChapterExample example = new ChapterExample();
        example.or()
                .andCourseIdEqualTo(Integer.parseInt(courseId));
        List<Chapter> chapters = chapterMapper.selectByExample(example);
        if(chapters.isEmpty()){
            throw  new NullSringException("该课程下暂无任何章节");
        }else {
            return chapters;
        }
    }

    @Override
    public List<Chapter> findChapterByForm(String courseId,String chapterName, String chapterInfo, String kaishitime, String jieshutime, String status) throws NullSringException {
        ChapterMapper chapterMapper= (ChapterMapper) ObjectFactory.getObject("ChapterMapper");
        List<Chapter> list  = chapterMapper.selectChapterByForm(courseId,chapterName,chapterInfo,kaishitime,jieshutime,status);
        if(list.isEmpty()){
            throw new NullSringException("未查询到符合要求的数据");
        }else {
            return list;
        }

    }

    @Override
    public void yongChapterById(String courseId, String chapterId, String status) throws Exception {
        CourseMapper courseMapper= (CourseMapper) ObjectFactory.getObject("CourseMapper");
        ChapterMapper chapterMapper= (ChapterMapper) ObjectFactory.getObject("ChapterMapper");
        Course course = courseMapper.selectByPrimaryKey(Integer.parseInt(courseId));
        Chapter chapter = chapterMapper.selectByPrimaryKey(Integer.parseInt(chapterId));
        if(status.equals("1") && CourseConstant.COURSE_STATUS_JINYONG.equals(""+course.getStatus())){
            throw new NoQuanXianException(course.getCourseName()+"已被禁用，该课程下的章节无法启用");
        }
        if(!status.equals(""+chapter.getStatus())){
            chapter.setStatus(Integer.parseInt(status));
            chapterMapper.updateByPrimaryKeySelective(chapter);
            //这里需要调用禁用资源的方法，比保证课程被禁用，其资源也被禁用
            ResourceMapper resourceMapper = (ResourceMapper) ObjectFactory.getObject("ResourceMapper");
            ResourceService resourceService = (ResourceService) ObjectFactory.getObject("ResourceServiceTarget");
            ResourceExample example =new ResourceExample();
            example.or().andChapterIdEqualTo(chapter.getId());
            List<Resource> list = resourceMapper.selectByExample(example);
            if(!list.isEmpty()){
                for (Resource r:list) {
                    resourceService.yongResource(""+r.getId(),status);
                }
            }


            //这里需要调用禁用资源的方法，比保证课程被启用，其资源也被启用
        }

    }

    @Override
    public void jianchaTitle(String chapterId,String courseId, String title) throws NullSringException, CharpetExistException {
        if(ParameterUtil.isNull(title)){
            throw new NullSringException("章节标题不可为空");
        }
        ChapterMapper chapterMapper = (ChapterMapper) ObjectFactory.getObject("ChapterMapper");
        ChapterExample example =new ChapterExample();
        if(ParameterUtil.isNull(chapterId)){
            example.or()
                    .andCourseIdEqualTo(Integer.parseInt(courseId))
                    .andTitleEqualTo(title);
        }else {
            example.or()
                    .andCourseIdEqualTo(Integer.parseInt(courseId))
                    .andTitleEqualTo(title)
                    .andIdNotEqualTo(Integer.parseInt(chapterId));
        }

        List<Chapter> list = chapterMapper.selectByExample(example);
        if(!list.isEmpty()){
            throw new CharpetExistException("相同课程下不可以有同名章节");
        }
    }

    @Override
    public void jianchaInfo(String info) throws NullSringException {
        if(ParameterUtil.isNull(info)){
            throw new NullSringException("内容详情不可为空");
        }
    }

    @Override
    public void jianchaZhiyuantitle(String zhiyuantitle) throws NullSringException, ResourceExistException {
        if(ParameterUtil.isNull(zhiyuantitle)){
            throw new NullSringException("资源标题不可为空");
        }
        ResourceMapper ResourceMapper = (ResourceMapper) ObjectFactory.getObject("ResourceMapper");
        ResourceExample example = new ResourceExample();
        example.or()
                .andTitleEqualTo(zhiyuantitle);
        List<Resource> resources = ResourceMapper.selectByExample(example);
        if(!resources.isEmpty()){
            throw new ResourceExistException("标题已存在请跟换");
        }
    }

    @Override
    public void jianchaCostNum(String costNum) throws NullSringException, TpyeException {
        if(ParameterUtil.isNull(costNum)){
            throw new NullSringException("花费值不可为空");
        }
        if(!costNum.matches("^[1-9]\\d*$")){
            throw new TpyeException("花费值格式错误，只可为数字");
        }
    }

    @Override
    public void jianchaResource( List<CommonsMultipartFile> list, String resourceType) throws NullSringException, TpyeException, BuPiPeiException {
        if(list.isEmpty()){
           throw new NullSringException("资源不可为空");
        }
        CommonsMultipartFile file = list.get(0);
        String filename = file.getOriginalFilename();
        if(ParameterUtil.isNull(filename)){
            throw new NullSringException("资源不可为空");
        }
        System.out.println("文件名"+filename);
        if(!filename.endsWith("pdf") && !filename.endsWith("mp4")){
            throw new TpyeException("资源格式不正确，只支持pdf和mp4格式");
        }
        String fileEnd = filename.substring(filename.lastIndexOf("."));
        if(resourceType==null || resourceType.equals("-1")){
            throw new NullSringException("资源格式未选择，请选择");
        }
        if(resourceType.equals("1")){
            resourceType=".mp4";
        }
        if(resourceType.equals("2")){
            resourceType=".pdf";
        }
        if(!resourceType.equals(fileEnd)){
            throw new BuPiPeiException("资源和资源格式不匹配");
        }
    }

    @Override
    public void addChapterAndResource(HttpSession session, String title, String info, String resourceTitle, String costType, String costNum, String resourceType, List<CommonsMultipartFile> list) throws Exception {
        String courseId = (String) session.getAttribute("courseId");
        ChapterMapper chapterMapper= (ChapterMapper) ObjectFactory.getObject("ChapterMapper");
        ResourceMapper resourceMapper = (ResourceMapper) ObjectFactory.getObject("ResourceMapper");
        CourseMapper courseMapper = (CourseMapper) ObjectFactory.getObject("CourseMapper");
        CommonsMultipartFile file = list.get(0);
        try {
            Course course = courseMapper.selectByPrimaryKey(Integer.parseInt(courseId));
            System.out.println("courseId="+courseId);
            Chapter chapter = new Chapter();
            chapter.setCourseId(Integer.parseInt(courseId));
            chapter.setTitle(title);
            chapter.setInfo(info);
            chapter.setCreateDate(new Date());
            chapter.setStatus(course.getStatus());//初始状态和课程一致
            chapterMapper.insertSelective(chapter);//已经在ChapterMapper.xml中修改过，该方法已被改成返回主键的了。
            Integer chapterId=chapter.getId();//取出返回的主键
            System.out.println("返回的主键："+chapterId);


            Resource resource=new Resource();
            resource.setTitle(resourceTitle);
            resource.setCoverImageUrl(course.getCoverImageUrl());//默认使用所在课程的图片
            resource.setOriginalName(file.getOriginalFilename());
            resource.setFileSize(ParameterUtil.fileSizeToMB(file.getSize()));//fileSizeToMB为自定义的工具类方法，把long转换成字符串
            System.out.println(resource.getFileSize());
            if(resourceType.equals("1")){
                resource.setFileType(ResourceConstant.RECOURSE_1_TYPE_MP4);
            }
            if(resourceType.equals("2")){
                resource.setFileType(ResourceConstant.RECOURSE_2_TYPE_PDF);
            }
            resource.setClickCount(Integer.parseInt(ResourceConstant.RECOURSE_CLICK_COUNT_KAISHI));
            resource.setCreateDate(new Date());
            if(costType.equals(ResourceConstant.RECOURSE_COST_JIFEN)){
                resource.setCostType(Integer.parseInt(ResourceConstant.RECOURSE_COST_JIFEN));
            }
            if(costType.equals(ResourceConstant.RECOURSE_COST_JINBI)){
                resource.setCostType(Integer.parseInt(ResourceConstant.RECOURSE_COST_JINBI));
            }
            resource.setCostNumber(Integer.parseInt(costNum));
            User user= (User) session.getAttribute("loginUser");
            resource.setUserId(user.getId());//默认未登录者的id
            resource.setChapterId(chapterId);
            resource.setStatus(course.getStatus());
            String path = ResourceConstant.RECOURSE_PATH+new SimpleDateFormat("yyyyMMdd").format(new Date());
            String context = session.getServletContext().getRealPath(path);
            System.out.println(context);
            new File(context).mkdirs();
            String fileName = file.getOriginalFilename();
            fileName =fileName.substring(0,fileName.lastIndexOf("."))
                    +new Date().getTime()+
                    fileName.substring(fileName.lastIndexOf("."));
            String resourcePath = path+"/"+fileName;
            System.out.println("数据库的数据="+resourcePath);
            resource.setPath(resourcePath);

            resourceMapper.insertSelective(resource);
            file.transferTo(new File(context,fileName));
        } catch (Exception e) {
            throw e;
        }


    }

    @Override
    public Chapter findChapterAndResourceByChapterId(String chapterId) {
        ChapterMapper chapterMapper = (ChapterMapper) ObjectFactory.getObject("ChapterMapper");
        return chapterMapper.selectChapterAndResourceByChapterId(chapterId);
    }

    @Override
    public void modifyChapterAndResource(HttpSession session, String chapterId, String title, String info, String resourceTitle, String costType, String costNum, String resourceType, List<CommonsMultipartFile> list) throws Exception {
        ChapterMapper chapterMapper= (ChapterMapper) ObjectFactory.getObject("ChapterMapper");
        ResourceMapper resourceMapper = (ResourceMapper) ObjectFactory.getObject("ResourceMapper");
        CommonsMultipartFile file = list.get(0);
        try {
            ResourceExample example = new ResourceExample();
            example.or()
                    .andChapterIdEqualTo(Integer.parseInt(chapterId));
            List<Resource> list1 = resourceMapper.selectByExample(example);
            Chapter chapter = new Chapter();
            chapter.setId(Integer.parseInt(chapterId));
            chapter.setTitle(title);
            chapter.setInfo(info);
            chapterMapper.updateByPrimaryKeySelective(chapter);

            Resource resource = list1.get(0);
            resource.setTitle(resourceTitle);
            if(resourceType.equals("1")){
                resource.setFileType(ResourceConstant.RECOURSE_1_TYPE_MP4);
            }
            if(resourceType.equals("2")){
                resource.setFileType(ResourceConstant.RECOURSE_2_TYPE_PDF);
            }
            if(costType.equals(ResourceConstant.RECOURSE_COST_JIFEN)){
                resource.setCostType(Integer.parseInt(ResourceConstant.RECOURSE_COST_JIFEN));
            }
            if(costType.equals(ResourceConstant.RECOURSE_COST_JINBI)){
                resource.setCostType(Integer.parseInt(ResourceConstant.RECOURSE_COST_JINBI));
            }
            resource.setCostNumber(Integer.parseInt(costNum));
            String context="";
            String fileName="";
            if(!ParameterUtil.isNull(file.getOriginalFilename())){
                String path = ResourceConstant.RECOURSE_PATH+new SimpleDateFormat("yyyyMMdd").format(new Date());
                context = session.getServletContext().getRealPath(path);
                System.out.println(context);
                new File(context).mkdirs();
                fileName = file.getOriginalFilename();
                fileName =fileName.substring(0,fileName.lastIndexOf("."))
                        +new Date().getTime()+
                        fileName.substring(fileName.lastIndexOf("."));
                String resourcePath = path+"/"+fileName;
                System.out.println("数据库的数据="+resourcePath);
                resource.setPath(resourcePath);
                resource.setFileSize(ParameterUtil.fileSizeToMB(file.getSize()));//fileSizeToMB为自定义的工具类方法，把long转换成字符串
                System.out.println(resource.getFileSize());
            }
            resourceMapper.updateByPrimaryKey(resource);
            if(!ParameterUtil.isNull(file.getOriginalFilename())){
                file.transferTo(new File(context,fileName));
            }
        } catch (Exception e) {
            throw e;
        }


    }
}
